﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.Threading.Tasks;
using System.IO.Ports;
using LRSystem;

namespace LRSystem
{
    public class LoWOTSerialPort : ISender
    {
        private SerialPort serialport;
        private List<byte> rxPacket = new List<byte>();
        public delegate void ParsePacketDelegate(object sender, List<byte> rxPkt);
        public event ParsePacketDelegate EvParsePacket;

        public string PortName { get; set; }
        public int BaudRate {get; set;}

        public LoWOTSerialPort(string portName, int baudrate)       // 该构造函数使用默认的数据解析                     
        {
            serialport = new SerialPort(portName, baudrate);
            serialport.BaudRate = baudrate;                              // 设置波特率
            serialport.PortName = portName;                              //  
            PortName = portName;
            BaudRate = baudrate;
            serialport.DataReceived += DataReceivedHandler;
            this.EvParsePacket += LoWOTOriginalPacket.PacketParse;       // 数据处理接收事件
        }

        public LoWOTSerialPort(string portName, int baudrate, ParsePacketDelegate evPrasePacket)  //该构造函数可自行设计解析函数
        {
            serialport.BaudRate = baudrate;
            serialport.PortName = portName;
            PortName = portName;
            BaudRate = baudrate;
            serialport.DataReceived += DataReceivedHandler;
            this.EvParsePacket += evPrasePacket;                       // 数据处理接收事件 
        }

        public void Open()
        {
            serialport.Open();
        }

        public void Close()
        {
            serialport.Close();
        }
        
        private void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
        {

                SerialPort sp = (SerialPort)sender;
                int btoread = sp.BytesToRead;
                byte by;


                for (int i = 0; i < btoread; i++)
                {
                    by = (byte)sp.ReadByte();
                    rxPacket.Add(by);                                    // 将收到的所有数据存入list.
                }
                if (EvParsePacket != null)
                    EvParsePacket(sender, rxPacket);                             // 对收到的数据进行解析处理
        }


        //public void SendPacket(ISendPacket packet)
        //{
        //    byte[] Buf = packet.BuildCmd();
        //    if (Buf != null)
        //        serialport.Write(Buf, 0, Buf.Length);
        //}

    }
}
